<script setup="">
import {onMounted, ref, defineEmits} from "vue"
import {Plus} from "@element-plus/icons-vue"
import {
  adminAddProduct,
  adminGetColumn,
  adminParseLink,
  adminPostTweet, adminUpdateProduct,
  adminUpdateTweet
} from "@/request/mid_interface.js";
import {ElMessage, ElMessageBox} from "element-plus";
import axios from "axios";
import {Close} from "@element-plus/icons-vue"

const props = defineProps({
  param: {
    type: Object,
    required: false,
  }
})

const emit = defineEmits(["refresh", "close"]);

onMounted(() => {
  if (!props.param || !props.param.product_id) {
  } else {
    const {
      product_id,
      product_image_url,
      group_link,
      title,
      content,
      is_featured,
    } = props.param
    productID.value = product_id
    productImageUrl.value = product_image_url
    groupLink.value = group_link
    productTitle.value = title
    productContent.value = content
    isFeatured.value = is_featured ? "是" : "否"
  }
})

async function confirmSend() {
  if (!productID.value) {
    // 新建发布
    const postParam = {
      "img_list": productImageUrl.value,
      "group_link": groupLink.value,
      "title": productTitle.value,
      "introduction": productContent.value,
      "is_feature": isFeatured.value === "是"
    }
    const res = await adminAddProduct(postParam)
    if (res.code) {
      ElMessage.success("发布成功！")
      emit('refresh')
    } else {
      ElMessage.warning("请将信息填写完整")
    }
  } else {
    // 更新发布
    const postParam = {
      "product_id": productID.value,
      "img_list": productImageUrl.value,
      "group_link": groupLink.value,
      "title": productTitle.value,
      "introduction": productContent.value,
      "is_feature": isFeatured.value === "是"
    }
    const res = await adminUpdateProduct(postParam)
    if (res.code) {
      ElMessage.success("编辑成功！")
      emit('refresh')
    } else {
      ElMessage.warning("请将信息填写完整")
    }
  }
}

const fileInput = ref(null)

function howGetLink() {
  ElMessageBox.alert('快团团小程序-订单管理-分享-插入公众号-团购页面路径-复制', '如何获取链接', {
    confirmButtonText: '确认',
    callback: (action) => {

    },
  })
}

function uploadImg(e) {
  let formData = new FormData()
  // 在这里写代码，判断文件是否为图片且大小小于2MB
  let file = e.target.files[0]
  if (file.size > 2 * 1024 * 1024) {
    ElMessage.warning("需上传图片文件，且图片大小小于2MB")
    return
  }
  formData.append('file', e.target.files[0])
  axios.post('/api/img/upload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
      'token': localStorage.token,
    }
  }).then(res => {
    productImageUrl.value = res.data.data
    console.log(res.data.data)
  }).catch(error => {
    console.log(error)
  })
}

function uploadImgBtn() {
  fileInput.value.click()
}

const featuredOptions = [
  {
    value: '是',
    label: '是',
  },
  {
    value: '否',
    label: '否',
  },
]

const productID = ref(0)
const productImageUrl = ref("")
const groupLink = ref("")
const productTitle = ref("")
const productContent = ref("")
const isFeatured = ref("是")

</script>

<template>
  <div class=" px-24 py-8">
    <input type="file" accept="image/*" ref="fileInput" style="display: none" @change="uploadImg">

    <!-- 请上传图片 -->
    <div class="flex items-center mt-6">
      <div style="width: 94px">请上传图片</div>
      <div class="relative" v-if="productImageUrl">
        <el-image
            style="width: 100px; height: 100px"
            :src="productImageUrl"
            :zoom-rate="1.2"
            :max-scale="7"
            :min-scale="0.2"
            :preview-src-list="[productImageUrl]"
            :initial-index="4"
            fit="cover"
        />
        <div @click="productImageUrl=''"
             class="cursor-pointer absolute right-1 top-1 w-5 h-5 flex justify-center items-center"
             style="background: rgba(0,0,0,0.3)">
          <el-icon color="white">
            <Close/>
          </el-icon>
        </div>
      </div>
      <div @click="uploadImgBtn" v-if="!productImageUrl"
           class="w-24 h-24 flex justify-center items-center bg-gray-100 rounded">
        <el-icon class="" style="">
          <Plus/>
        </el-icon>
      </div>
    </div>

    <!-- 拼团链接 -->
    <div class="flex items-center mt-6">
      <div class="w-28">拼团链接</div>
      <el-input
          v-model="groupLink"
          placeholder="请输入拼团链接"
          class=""
          size="large"
      >
        <template #append>
          <div @click="howGetLink" class="cursor-pointer select-none">如何获取链接？</div>
        </template>
      </el-input>
    </div>


    <!-- 商品标题 -->
    <div class="flex items-center mt-6">
      <div class="w-28">商品标题</div>
      <el-input
          v-model="productTitle"
          placeholder="请输入商品的标题"
          class=""
          size="large"
      >
      </el-input>
    </div>

    <!-- 商品介绍 -->
    <div class="flex items-center mt-6">
      <div class="w-28">商品介绍</div>
      <el-input
          v-model="productContent"
          placeholder="请输入商品的介绍内容"
          type="textarea"
          rows="6"
      >
      </el-input>
    </div>

    <!-- 是否精选 -->
    <div class="flex items-center mt-6">
      <div style="width: 94px">是否精选</div>
      <el-select
          v-model="isFeatured"
          class="m-2 flex-1"
          placeholder="请选择是否精选"
          size="large"
      >
        <el-option
            v-for="item in featuredOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
        />
      </el-select>
    </div>

    <div class="flex justify-center mt-16">
      <div @click="emit('close')"
           class="cursor-pointer select-none hover:opacity-70 px-5 py-2 border rounded font-bold">取消
      </div>
      <div @click="confirmSend"
           class="cursor-pointer select-none hover:opacity-70 px-5 py-2 border rounded font-bold ml-3 text-white"
           style="background: var(--themeColor); border: var(--themeColor);">确认保存
      </div>
    </div>

  </div>
</template>

<style scoped>
* {
  --el-pagination-hover-color: var(--themeColor);
  --el-input-focus-border-color: var(--themeColor);
}

/deep/ .el-dialog {
  border-radius: 20px !important;
}

/deep/ .m-2 {
  margin: 0;
}

/deep/ .el-input__wrapper {
  box-shadow: 0 0 0 1px #eee inset;
}

/deep/ .el-select__wrapper {
  box-shadow: 0 0 0 1px #eee inset;
}

/deep/ .el-input-group__append {
  transform: translateX(-1px);
  box-shadow: 0 0 0 1px #eee inset;
}
</style>
